﻿var gXmlDocument;
var eButton;
var targetFrame;
var xmlQueryDoc;
window.onload = Pointfocus;
//window.document.onkeydown = On_Keydown;
if (document.addEventListener) {
    document.addEventListener("keypress", EventHandler_KeyDown);
    document.addEventListener("mousedown", EventHandler_MouseDown);
} else if (document.attachEvent) {
    document.attachEvent("onkeypress", EventHandler_KeyDown);
    document.attachEvent("onmousedown", EventHandler_MouseDown);
}
//document.onkeypress = EventHandler_KeyDown;
//document.onmousedown = EventHandler_MouseDown;
//---------------------------------------------------------------------------------------
/*
	函式功能: 設定XML與DataGrid作資料連繫
	傳入值 : XML Document 格式資料
	傳出值 : null
*/

window.showModalDialog = function (url, name, specs, replace) {

    var wStr = (/dialogWidth=(\w+)?;/i.exec(specs)[1]);
    var hStr = (/dialogHeight=(\w+)?;/i.exec(specs)[1]);

    var w = wStr.toLowerCase().replace("px", "");
    var h = hStr.toLowerCase().replace("px", "");

    w = parseInt(w) + 100;
    h = parseInt(h) + 100;

    var left = (screen.width / 2) - (w / 2);
    var top = (screen.height / 2) - (h / 2);

    /* IE 11 not support
    if (typeof window.screenLeft !== 'undefined') {
        screenLeft = window.screenLeft;
        screenTop = window.screenTop;
    } else if (typeof window.screenX !== 'undefined') {
        screenLeft = window.screenX;
        screenTop = window.screenY;
    }
    left += screenLeft;
    top += screenTop;
    */
    specs = specs.replace("dialogWidth", "width");
    specs = specs.replace("dialogHeight", "height");
    specs = specs.replace(wStr, w);
    specs = specs.replace(hStr, h);
    specs = specs.replace("center=yes;", "");
    specs = specs.replace("border=thin;", "");
    specs = specs.replace("help=no;", "");
    specs = specs.replace(";", ",");
    specs += "toolbar=no;titlebar=no;location=no;directories=no;menubar=no;scrollbars=yes"
    specs += ';top=' + top + ';left=' + left;

    //Ken20140716
    var result = window.open(url, "name", specs, replace);
    //IE 11 not support
    //result.moveTo(left, top);

}

function DataBind(XmlDoc, bindFrame) {
    try {
        eButton = event.srcElement;
        if (eButton != null)
            eButton.disabled = true;

        //將XML存入HTMLDocument (submit的 xml 資料)
        InsertXML(xmlQueryDoc.xml);

        //取得下一頁之index
        var pageindex = XmlDoc.selectSingleNode("//Position");
        if (pageindex != undefined) {
            if (targetFrame != undefined) {
                targetFrame.row_count.lang = pageindex.text;
            }
        }

        //指定全域變數
        gXmlDocument = XmlDoc;

        //可由使用指定連結的框架

        if (bindFrame == undefined) {
            targetFrame = self;  //top.frames["main"];
        }
        else {
            targetFrame = bindFrame
        }
        //清除DataGrid 資料列

        var gridBodyTable = targetFrame.DataGrid.gridBodyTable;
        ClearTableRow(gridBodyTable);
        targetFrame.DataGrid.document.getElementById("imgConnect").style.display = "";

        //計時半秒執行產生資料
        timerID = window.setTimeout("DataLoad()", 1000);
    }
    catch (e) {
        if (eButton != null)
            eButton.disabled = false;

        return e;
    }
}

//---------------------------------------------------------------------------------------
/* 鎖定Button防止重複Submit   Creator By Titan*/
// 傳入參數說明 : elem 固定鎖定該物件，當網頁物件過多時使用，不傳時則鎖定網頁所有控制項 
var ButtonTargetEvent = null;
var EnableTimerID = null;
var TargetElement = null;
function Handler_SubmitButtonDisabled(elem) {
    TargetElement = elem;
    ButtonTargetEvent = event.srcElement;
    EnableTimerID = window.setTimeout("HandlerDisabled()", 100);
}
function HandlerDisabled() {
    if (TargetElement == null) {
        for (var i = 0 ; i < ButtonTargetEvent.form.elements.length ; i++)
            ButtonTargetEvent.form.elements[i].disabled = true;
    }
    else {
        TargetElement.disabled = true;
    }
}

//---------------------------------------------------------------------------------------
/*
	函式功能: 用於將XML資料與DataGrid作資料連繫
	傳入值 : XML Document 格式資料
	傳出值 : null
*/
function DataLoad() {
    try {
        //改由使用者指定

        //var targetFrame = top.frames["main"];
        var gridBodyTable = targetFrame.DataGrid.gridBodyTable;
        var BaseForm = targetFrame.document.forms[0];



        // 取得回傳的資料筆數 (查詢)
        var tablelists = gXmlDocument.selectNodes("//info");
        var pagesize = 0;
        for (var k = 0; k < 1; k++) {
            // 判斷交易結果 (查詢)
            pagesize = tablelists[k].getAttribute("pagesize");
            if (tablelists[k].selectSingleNode("ReturnCode").text == "000") {
                // 成功取得資料, 

                // 聯繫資料欄標題 (顯示欄位名稱 column name)
                var columnNames = tablelists[k].getAttribute("id") + "_Columns";
                AddgridBarCell(columnNames, gXmlDocument);

                //聯繫資料內容
                var rowDatas = "//" + tablelists[k].getAttribute("id") + "_Data";
                var dataCount = gXmlDocument.selectNodes(rowDatas + "/Items").length;
                for (var i = 0; i < dataCount; i++) {
                    //加入欄位資料
                    oTR = gridBodyTable.insertRow(i);
                    oRowNode = gXmlDocument.selectNodes(rowDatas + "//Items").item(i);

                    //開放checkbox 
                    if (BaseForm.chkALL.disabled) {
                        //是否開放明細資料
                        if (targetFrame.searchKey.Nodown == undefined)
                            AddRowCell(oTR, "<IMG src='images/point.gif' class='hand'>", "DataList", "center")
                        else {
                            if (targetFrame.searchKey.Return == undefined)
                                AddRowCell(oTR, "<IMG src=images/u1.gif >", "DataList", "center")
                            else
                                AddRowCell(oTR, "<IMG src='images/return.gif' class='hand' onclick='OnReturnValue();' >", "DataList", "center")
                        }
                    }
                    else
                        AddRowCell(oTR, "<input id='chklitem' type='checkbox'>", "DataList", "center")

                    for (var j = 1; j <= oRowNode.childNodes.length; j++) {
                        sInnerText = oRowNode.childNodes.item(j - 1).text;
                        AddRowCell(oTR, sInnerText, "DataList", "left");
                    }
                }

                // 設定搜尋結果之資料總筆數
                var data_from = parseInt(targetFrame.row_count.lang) + 1;
                var data_end = data_from + dataCount - 1;
                var data_rowcount = parseInt(tablelists[k].selectSingleNode("RowCount").text);
                if (gridBodyTable.lang == "zh-tw") {
                    targetFrame.row_count.innerText = "搜尋結果 共 "
                                                                    + data_rowcount + " 筆  ，目前位置 " + data_from + " 至 " + data_end + "  筆 ，"
                                                                    + "頁次 / 總頁數 ： " + Math.ceil(data_end / pagesize).toFixed(0) + " / " + Math.ceil(data_rowcount / pagesize).toFixed(0);
                }
                else {
                    targetFrame.row_count.innerText = "search result ， "
                                                                    + data_rowcount + " rows  ，current position " + data_from + " - " + data_end + "  row ，"
                                                                    + "page / total page ： " + Math.ceil(data_end / pagesize).toFixed(0) + " / " + Math.ceil(data_rowcount / pagesize).toFixed(0);
                }

                // 設定最後一頁的 position
                setPagePosition(data_from, data_end, parseInt(pagesize), data_rowcount);

            }
            else if (tablelists[k].selectSingleNode("ReturnCode").text == "100") {
                // 查無資料
                // 設定最後一頁的 position
                var i_position = parseInt(BaseForm.BtnNext.lang) - parseInt(pagesize);
                if (i_position >= 0) {
                    BaseForm.BtnPrev.lang = i_position;
                }
                else {
                    BaseForm.BtnPrev.lang = 0;
                }
                if (gridBodyTable.lang == "zh-tw")
                    targetFrame.row_count.innerText = "搜尋結果，查無任何的資料!";
                else
                    targetFrame.row_count.innerText = "search result ，Don't Find any data !";

                return;
            }
            else {
                // 失敗
                targetFrame.row_count.innerText = "搜尋結果，" + tablelists[k].selectSingleNode("Message").text + "!";
                ShowError(tablelists[k].selectSingleNode("Message").text);
                return;
            }
        }
    }
    catch (e) {
        if (gridBodyTable.lang == "zh-tw")
            throw new Error(e.message + '\n資料連繫錯誤,請重新確認 ! ');
        else
            throw new Error(e.message + '\nData Link Error,Please check ! ');
    }
    finally {
        targetFrame.DataGrid.document.getElementById("imgConnect").style.display = "none";
        if (eButton != null)
            eButton.disabled = false;
        //當最後一頁時把下一頁鎖定

        BaseForm.BtnNext.disabled = data_rowcount == data_end ? true : false;

    }
}
//---------------------------------------------------------------------------------------
/*
	函式功能: 新增單一資料列中的資料欄
	傳入值 : oTR=目標表ROW,sHTML=呈現資料,sClass=呈現的樣式,sAlign=對齊位置
	傳出值 : null
	
*/
function AddRowCell(oTR, sHTML, sClass, sAlign) {
    try {
        //var targetFrame = top.frames["main"];
        var cellindex = oTR.cells.length;
        var oTD = oTR.insertCell(cellindex);
        with (oTD) {
            style.width = targetFrame.gridBar.rows(0).cells(cellindex).style.width;
            className = sClass;
            innerHTML = sHTML + "&nbsp;";
            align = sAlign;
        }
    }
    catch (e) {
        throw e;
    }
}
//---------------------------------------------------------------------------------------

function AddgridBarCell(columnNames, oXmlDoc) {
    try {
        var oTD = null;
        //var targetFrame = top.frames["main"];
        var tagetRow = targetFrame.gridBar.rows(0);
        var sSort = targetFrame.XMLExecSchema.selectNodes("//command")[0].getAttribute("sort");

        var tagColumnNames = "//" + columnNames + "/Column";
        //當欄位數不相等時刪除資料欄



        while (tagetRow.cells.length - 1 > oXmlDoc.selectNodes(tagColumnNames).length) {
            tagetRow.deleteCell(tagetRow.cells.length - 1)
        }

        //當欄位數不相等時加入資料欄



        //while(oXmlDoc.selectNodes("//Column").length>tagetRow.cells.length-1)
        while (oXmlDoc.selectNodes(tagColumnNames).length > tagetRow.cells.length - 1) {
            oTD = tagetRow.insertCell(tagetRow.cells.length)
            with (oTD) {
                className = "header";
                align = "center";
            }
        }

        for (var i = 0; i < oXmlDoc.selectNodes(tagColumnNames).length; i++) {
            var tagetCell = tagetRow.cells(i + 1);
            with (tagetCell) {
                id = oXmlDoc.selectNodes(tagColumnNames)[i].getAttribute("id");

                //判斷昇降冪圖示

                if (id == sSort.toUpperCase())
                    innerHTML = oXmlDoc.selectNodes(tagColumnNames)[i].getAttribute("name") + "&nbsp;<img src='../images/bar_up.gif'>";
                else if (sSort == id + " DESC")
                    innerHTML = oXmlDoc.selectNodes(tagColumnNames)[i].getAttribute("name") + "&nbsp;<img src='../images/bar_down.gif'>";
                else
                    innerText = oXmlDoc.selectNodes(tagColumnNames)[i].getAttribute("name");

                //填入原來設定的寬度

                style.width = tagetCell.style.width;
            }
        }
        //加入 refresh image  
        olastTD = tagetRow.insertCell(tagetRow.cells.length)
        with (olastTD) {
            width = "2%";
            innerHTML = "<img src='../images/grid_Refresh.gif'>";
            className = "header";
            align = "center";
        }
    }
    catch (e) {
        throw e;
    }
}

//---------------------------------------------------------------------------------------
/*
	函式功能: 執行查詢的資料庫命令
	傳入值 : sXmlCommand=命令字串,sSort = 欄位,sPageIndex=頁次索引值



	傳出值 : responseXML 查詢資料後的結果
*/
function ExecuteQuery(sXmlCommand, sSort, sPageIndex) {
    try {
        //宣告XMLHTTP 物件
        var xhttp = GetXmlHttp();
        xmlQueryDoc = new ActiveXObject("Microsoft.XMLDOM");        
        xmlQueryDoc.async = false;
        xmlQueryDoc.loadXML(sXmlCommand);

        // 排序僅對 xml 的第一組查詢語法


        var command = xmlQueryDoc.selectNodes("//command")[0];
        if (sSort != undefined && sSort != "")
            command.setAttribute("sort", sSort);

        if (sPageIndex != undefined && "" + sPageIndex != "") {
            command.setAttribute("pageindex", sPageIndex);
            if (targetFrame != undefined) {
                targetFrame.row_count.lang = sPageIndex;
            }
        }


        //開啟與server的通道
        var hostAddress = document.location.protocol + "//" + document.location.host;
        xhttp.open("POST", hostAddress + "/smasb2b/ServiceAgent.aspx", false);

        //將資料傳送至server
        xhttp.send(xmlQueryDoc);

        //判斷連接狀態是否成功

        if (xhttp.status == 304) {
            alert("您閒置網站的時間已經超過設定時間，必須重新登入 !!");
            window.open(document.location.protocol + "//" + document.location.host + "//smasb2b//" + "default.aspx", "smasb2b", "height=" + (window.screen.availHeight - 45) + ", width=" + (window.screen.availWidth - 10) + ", top=0, left=0, menubar=0, location=0, resizable=1, status=1")
            this.close();
        }
        if (xhttp.status != 200) {
            alert('執行發生錯誤\n' + xhttp.statusText)
            this.close();
        }
        return xhttp.responseXML;
    }
    catch (e) {
        switch (e.name) {
            case "Error":
                throw new Error('函式ExecuteQuery() -' + e.message); break;
            case "TypeError":
                throw new Error('函式ExecuteQuery() - 執行XML格式不正確,重新確認!'); break;
        }
    }
    finally {
        xhttp = null;
    }
}
//---------------------------------------------------------------------------------------
/*
	函式功能: 將XML與畫面資料進行資料結合
	傳入值 : xmlDocument = 查詢XML結果
	傳出值 : null
*/
function DataView(xmlDocument) {
    var ControlID = null;
    try {
        var currNode = null;
        xmlDocument.setProperty("SelectionLanguage", "XPath");
        var htmlDocument = document.forms[0].elements;
        for (i = 0; i < htmlDocument.length; i++) {
            ControlID = htmlDocument[i].id;
            switch (htmlDocument[i].type) {
                case "text":
                    htmlDocument[i].value = xmlDocument.selectSingleNode("//items/item[@id='" + htmlDocument[i].id + "']").text;
                    if (xmlDocument.selectSingleNode("//items/item[@id='" + htmlDocument[i].id + "']").getAttribute("ref") != null) {
                        var RefNameSpan = document.createElement("SPAN");
                        RefNameSpan.ID = "spn" + ControlID
                        RefNameSpan.className = "refSpan"
                        RefNameSpan.innerHTML = xmlDocument.selectSingleNode("//items/item[@id='" + htmlDocument[i].id + "']").getAttribute("ref");
                        htmlDocument[i].parentElement.insertBefore(RefNameSpan);
                    }
                    break;
            }
        }
    }
    catch (e) {
        throw new Error("'[" + ControlID + "]' 無相符資料!");
    }
}

function OpenViewDialog(DialogUrl, id1, id2, id3, id4, id5, id6) {
    var ArrOfArgu = new Array(id1, id2, id3, id4, id5, id6)
    return window.showModalDialog(DialogUrl, ArrOfArgu, 'dialogWidth=620px;dialogHeight=450px;center=yes;border=thin;help=no;status=no;resizable=no;', true)
}
//---------------------------------------------------------------------------------------

function URLQueryString(ParamID) {
    ArrOfURL = document.URLUnencoded.split("?");
    var Url = ArrOfURL[0];
    var Params = ArrOfURL[1];
    if (Params != null) {
        ArrOfParam = Params.split("&");
        var ArrOfKey = new Array(ArrOfParam.length);
        var ArrOfVal = new Array(ArrOfParam.length);
        for (var i = 0 ; i < ArrOfParam.length ; i++) {
            if (ArrOfParam[i].search("=") != -1) {
                ArrOfKey[i] = ArrOfParam[i].split("=")[0].toUpperCase();
                ArrOfVal[i] = ArrOfParam[i].split("=")[1].toUpperCase();
            }
        }
        if (ArrayIndexOf(ArrOfKey, ParamID.toUpperCase()) != -1)
            return ArrOfVal[ArrayIndexOf(ArrOfKey, ParamID.toUpperCase())];
        else
            return "";
    }
    else {
        return "";
    }
}

function ArrayIndexOf(ArraySet, ID) {
    for (var i = 0; i < ArraySet.length; i++) {
        if (ArraySet[i] == ID)
            return i
    }
    return -1
}
//---------------------------------------------------------------------------------------

function InsertXML(innerHTML) {
    var targetFrame;
    if (top.frames["main"] != undefined)
        targetFrame = top.frames["main"];
    else
        targetFrame = self;

    var xmlDocument = targetFrame.document.createElement("XML");
    xmlDocument.id = "XMLExecSchema";
    xmlDocument.innerHTML = innerHTML;
    try {
        targetFrame.document.body.removeChild(targetFrame.XMLExecSchema);
        targetFrame.document.body.insertBefore(xmlDocument);
    }
    catch (e) {
        targetFrame.document.body.insertBefore(xmlDocument);
    }
}
//---------------------------------------------------------------------------------------

/*
	函式功能: 清除HTML表格資料列


	傳入值 : oTable=目的表格
	傳出值 : null
*/
function ClearTableRow(oTable) {
    try {
        while (oTable.rows.length > 0) {
            oTable.deleteRow(oTable.rows.length - 1);
        }
    }
    catch (e) {
        return e;
    }
}
//---------------------------------------------------------------------------------------

//控制錯誤資料及秀錯誤訊息
function ShowError(Message) {
    alert(Message);
}

/*
	函式功能: 依 client 端的系統, 取得不同的 msxml 版本物件
	傳入值 : void
	傳出值 : msxml 物件
*/
function GetXmlHttp() {
    var XmlVersion = 4;

    try {
        xmldom = new ActiveXObject("MSXML2.DOMDocument.4.0");
    } catch (e) {
        XmlVersion = 3;
    }

    if (XmlVersion == 4) {
        return new ActiveXObject("MSXML2.XMLHTTP.4.0");
    }
    else {
        return new ActiveXObject("MSXML2.XMLHTTP");
    }
}
//---------------------------------------------------------------------------------------

/*
	函式功能: 設定第一頁, 上一頁, 下一頁, 下一頁的 position 位置
	傳入值 : void
	傳出值 : void
*/
function setPagePosition(p_from, p_end, p_pagesize, p_rowcount) {

    targetFrame.document.getElementById("PageIndex").lang = p_pagesize;
    targetFrame.document.getElementById("PageIndex").rowcount = p_rowcount;
    //alert(p_from + " :: " + p_end + " :: " + p_pagesize + " :: " + p_rowcount);
    // 第一頁的 (absolute position 固定從第 0 筆開始)
    targetFrame.document.getElementById("BtnFirst").lang = 0;

    // 上一頁



    if (p_from - 1 - p_pagesize >= 0) {
        targetFrame.document.getElementById("BtnPrev").lang = p_from - 1 - p_pagesize;
    }
    else {
        targetFrame.document.getElementById("BtnPrev").lang = 0;
    }

    // 下一頁



    targetFrame.document.getElementById("BtnNext").lang = p_end;

    // 最後頁
    if (p_end - p_pagesize >= 0) {
        targetFrame.document.getElementById("BtnLast").lang = (Math.ceil(p_rowcount / p_pagesize) * p_pagesize) - p_pagesize;
    }
    else {
        targetFrame.document.getElementById("BtnLast").lang = 0;
    }
}
//---------------------------------------------------------------------------------------

/*
	函式功能: 執行異動資料庫命令


	傳入值 : sXmlCommand=命令字串
	傳出值 : responseXML 資料交易後的結果
*/
function ExecuteNonQuery(sXmlCommand) {
    try {
        //宣告XMLHTTP 物件
        //var xhttp = new ActiveXObject("Msxml2.XMLHTTP.4.0");
        var xhttp = GetXmlHttp();
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = false;
        xmlDoc.loadXML(sXmlCommand);

        //開啟與server的通道
        var hostAddress = document.location.protocol + "//" + document.location.host;
        xhttp.open("POST", hostAddress + "/smasb2b/ServiceAgent.aspx", false);

        //將資料傳送至server
        xhttp.send(xmlDoc);

        //判斷連接狀態是否成功


        switch (xhttp.status) {
            case 404:
                throw new Error('連接網頁失敗, 請確認ServiceAgent.aspx檔案路徑!'); break;
        }

        var responseXML = xhttp.responseXML;

        xhttp = null;
        return responseXML;
    }
    catch (e) {
        switch (e.name) {
            case "Error":
                throw new Error('函式ExecuteQuery() -' + e.message);
                break;
            case "TypeError":
                throw new Error('函式ExecuteQuery() - 執行XML格式不正確,重新確認!');
                break;
        }
    }
}

//---------------------------------------------------------------------------------------
/*
	函式功能: 0.5秒後, 顯示訊息於訊息區
	傳入值 : msxml 物件
	傳出值 : void
*/
function DataMessageBind(XmlDoc) {
    //指定全域變數
    gXmlDocument = XmlDoc;

    //計時半秒執行產生資料
    timerID = window.setTimeout("DataMessageLoad()", 500);
}




//---------------------------------------------------------------------------------------
/*
	函式功能: 設定 focus 於畫面上的第一個欄位


	傳入值 : void
	傳出值 : void
*/
function setObjectFocus(p_name) {
    var objElements = targetFrame.document.forms[0].elements;
    var i_element_length = objElements.length;

    for (var i = 0; i < i_element_length; i++) {
        if (objElements[i].type == "text" ||
			objElements[i].type == "radio" ||
			objElements[i].type == "checkbox" ||
			objElements[i].type == "textarea") {
            if (objElements[i].disabled == false && objElements[i].readOnly == false) {
                objElements[i].focus();
                break;
            }
        }
        else if (objElements[i].type.indexOf("select") >= 0) {
            if (objElements[i].disabled == false) {
                objElements[i].focus();
                break;
            }
        }
    }
}

//---------------------------------------------------------------------------------------
/*
	函式功能: 建立表格中的Cells
	傳入值 : Table
	傳出值 : void
*/
function AddDetailCell(DestRow, cells) {
    try {
        for (j = 0; j < cells; j++) {
            DestRow.insertCell();
            DestRow.cells[j].className = "detail";
        }
    }
    catch (e) {
        ShowError(e.message);
    }
}
//---------------------------------------------------------------------------------------

/*
	函式功能: 建立元件
	傳入值 : type,name,size,value,checked,onchange,onclick,IsReadOnly,IsUpper
	傳出值 : string
*/
function CreaterInnerHTML(type, name, size, value, checked, onchange, onclick, IsReadOnly, IsUpper) {
    switch (type.toLowerCase()) {
        case "input":
            if (!IsReadOnly) {
                if (IsUpper)
                    return "<input type='" + type + "' size='" + size + "' name='" + name + "' value='" + value + "' onchange='" + onchange + "' onclick='" + onclick + "' class='text' onBlur='this.value = this.value.toUpperCase();' style='TEXT-TRANSFORM: uppercase'>"
                else
                    return "<input type='" + type + "' size='" + size + "' name='" + name + "' value='" + value + "' onchange='" + onchange + "' onclick='" + onclick + "' class='text'>"
            }
            else {
                return "<input type='" + type + "' size='" + size + "' name='" + name + "' value='" + value + "' onchange='" + onchange + "' onclick='" + onclick + "' readonly class='readonly' >"
            }
            break;
        case "hidden":
            return "<input type='" + type + "' size='" + size + "' name='" + name + "' value='" + value + "'>"
            break;
        case "select":
            break;
        case "checkbox":
            if (checked) {
                return "<input type='" + type + "' value='" + value + "' name='" + name + "' checked=true onclick='" + onclick + "'>"
            }
            else {
                return "<input type='" + type + "' value='" + value + "' name='" + name + "'onclick='" + onclick + "'>"
            }
            break;
        case "radio":
            break;
    }
}

//--------------------------------------------------------------------------------/
//維護程式 - 表單載入															  /
//功能:當表單載入時初始值														  /
//函式名稱 = subfrmload															  /
//--------------------------------------------------------------------------------/
function Pointfocus() {
    try {
        var count = 0;
        var firstObj;
        var found = false;
        for (var i = 0; i < document.forms.length; i++) {
            for (var j = 0; j < document.forms(i).elements.length; j++) {
                if (document.forms(i).elements(j).type == "text" && document.forms(i).elements(j).readOnly == false) {
                    count++;
                    if (count == 1) {
                        firstObj = document.forms(i).elements(j);
                    }
                    if (document.forms(i).elements(j).style.background == "#FFDFDC") {
                        firstObj = document.forms(i).elements(j);
                        found = true;
                        break;

                    }
                }
            }
            if (found) break;
        }
        if (firstObj != undefined) {
            firstObj.focus();
        }
    }
    catch (e) {
        //ShowError("Error : Pointfoucs()" + e.message);
        return false;
    }
    finally {
        delete count;
        delete firstObj;
        delete found;
    }
}
//---------------------------------------------------------------------------------------

/*
	函式功能: 顯示訊息於訊息區
	傳入值 : msxml 物件
	傳出值 : void
*/
/*function DataMessageLoad()
{
	try 
	{
		var messagelists = gXmlDocument.selectNodes("//info");
		
		if (messagelists[0].selectSingleNode("TransResult").text == "T") {
			// 
			var successObject = new Object();
			successObject.id = "re_message";
			successObject.Name = "成功";
			successObject.ErrMsg = "資料處理成功";
			ErrHandler_AddItem(successObject, false);
		}
		else {
			var errObject = new Object();
			errObject.id = "re_message";
			errObject.Name = "失敗";
			errObject.ErrMsg = messagelists[0].selectSingleNode("Message").text;
			ErrHandler_AddItem(errObject, false);
		}
	}		
	catch (e) {
		throw new Error(e.message + '\n資料連繫錯誤,請重新確認 ! ');
	}
}*/
//---------------------------------------------------------------------------------------

/*
	函式功能: 選取全部DataGrid item
	傳入值 : void
	傳出值 : void
*/
function gridSelectAll() {
    try {
        var vDataGrid = targetFrame.DataGrid.document;
        var BaseForm = targetFrame.document.forms[0];
        if (vDataGrid.all["chklitem"] != undefined) {
            for (i = 0 ; i < vDataGrid.all["chklitem"].length ; i++) {
                vDataGrid.all["chklitem"][i].checked = BaseForm.chkALL.checked;
            }
            if (i == 0) {
                vDataGrid.all["chklitem"].checked = BaseForm.chkALL.checked;
            }
        }
    }
    catch (e) {
        throw new Error("gridSelectAll() : " + e.message);
    }
}
//--------------------------------------------------------------------------------/
//維護程式 - 新增空白欄位 														  /
//功能:新增detail 行數 														  /
//函式名稱 = DialogBtnClientButtonCtrl1_OnClick												  /
//Table Name
//seq為序號的位置從0開始
//--------------------------------------------------------------------------------/
function AddDetailList(DetailTable, seq, rows) {
    try {

        if (rows == "" || rows == undefined)
            //2005/4/20以便沒傳ROWS也可以增加空白欄位by samantha
        {
            rows = 10;
        }
        var selectedIndex = DetailTable.rows.length;

        for (i = 0; i < rows; i++) {

            var DestRow = DetailTable.insertRow();
            AddDetailCell(DestRow, DetailTable.rows[0].cells.length);
            var row = DetailTable.rows.length - 1
            for (j = 0; j < DetailTable.rows[0].cells.length; j++) {

                HTML = DetailTable.rows[row - 1].cells[j].innerHTML
                if (j != seq)//seq不修改其id
                {
                    for (k = 0; k < DetailTable.rows[row - 1].cells[j].children.length; k++) {
                        if ((DetailTable.rows[row - 1].cells[j].children[k].name).substr(0, 1) != 'M') {
                            if (DetailTable.rows[row - 1].cells[j].children[k].tagName != "A") //hyperlink
                            {
                                HTML = HTML.replace(DetailTable.rows[row - 1].cells[j].children[k].name, DetailTable.rows[row - 1].cells[j].children[k].id + row)
                                switch (DetailTable.rows[row - 1].cells[j].children[k].type) {
                                    case "checkbox":
                                        HTML = HTML.replace("CHECKED", ""); break;
                                    case "hidden":
                                        if (DetailTable.rows[row - 1].cells[j].children[k].value != "") {
                                            value = "value=" + DetailTable.rows[row - 1].cells[j].children[k].value
                                            HTML = HTML.replace(value, "")
                                        }
                                        break;
                                    case "text":
                                        if (DetailTable.rows[row - 1].cells[j].children[k].value != "") {
                                            value = "value=" + DetailTable.rows[row - 1].cells[j].children[k].value
                                            HTML = HTML.replace(value, "")
                                        }
                                        break;
                                    case "select-one":
                                        if (DetailTable.rows[row - 1].cells[j].children[k].value != "") {
                                            value = "selected"
                                            HTML = HTML.replace(value, "")
                                        }
                                        break;
                                }
                            }
                            else {
                                if (DetailTable.rows[row - 1].cells[j].children[k].children.length > 0) {
                                    pr_row = rows - 1;
                                    value = "(" + pr_row + ")"
                                    value1 = "(" + rows + ")"
                                    HTML = HTML.replace(value, value1)
                                }
                                else {
                                    HTML = ""//hyperlink清為空白
                                }
                            }
                        }
                        else {
                            if (DetailTable.rows[row - 1].cells[j].children[k].value != "") {
                                value = "value=" + DetailTable.rows[row - 1].cells[j].children[k].value
                                HTML = HTML.replace(value, "value=A")
                            }

                        }

                    }
                }
                if (DetailTable.rows[row - 1].cells[j].children.length == 0) {
                    HTML = ""
                }
                DestRow.cells[j].innerHTML = HTML
                DestRow.cells[j].align = DetailTable.rows[row - 1].cells[j].align
                //修改為了，checkbox打勾時，所有欄位為readony時，再按下新增空白欄位的button，必需將欄位屬性改成可輸入，by vicky 94.5.2
                for (k = 0; k < DestRow.cells[j].children.length; k++) {
                    if (DestRow.cells[j].children[k].type == 'text' || DestRow.cells[j].children[k].type == 'number') {
                        DestRow.cells[j].children[k].value = ""
                        DestRow.cells[j].children[k].style.background = "#FFFFFF";
                        if ((DestRow.cells[j].children[k].className == 'text' || DestRow.cells[j].children[k].className == 'number') && DestRow.cells[j].children[k].readOnly) {
                            DestRow.cells[j].children[k].readOnly = false
                        }
                    }

                }

            }
            if (seq != undefined) {
                if (seq.toString() != "") {

                    DetailTable.rows[row].cells[parseInt(seq)].children[0].value = parseInt(DetailTable.rows[row - 1].cells[parseInt(seq)].children[0].value) + 1

                }
            }
        }
        //document.all[DetailTable.rows[0].cells[1].children[0].id+selectedIndex].select();
        //DetailTable.deleteRow(0);

    }
    catch (e) {
        ShowError(e.message);
    }
    finally {

    }
}
//---------------------------------------------------------------------------------------

/*
	函式功能: 控制onTextChange focus
	傳入值 : null
	傳出值 : null
*/
function On_Keydown() {
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    var e = event.srcElement;
    var i, j;
    try {
        if (keyCode == 9 && (e.tagName == "INPUT" || e.tagName == "SELECT")) {
            var self_form = event.srcElement.form;
            for (i = 0 ; i < self_form.elements.length ; i++)
                if (event.srcElement == self_form.elements[i])
                    break;


            for (j = i ; j < self_form.elements.length ; j++) {
                if (self_form.elements[j + 1].type != "hidden" && !self_form.elements[j + 1].readOnly && !self_form.elements[j + 1].disabled)
                    return;
                else
                    self_form.elements[j + 1].focus();
            }

        }
    }
    catch (e) {
        return;
    }
}
//---------------------------------------------------------------------------------------

/*
	Contorl Enter Key
*/
var TabIndex = 0;
function EventHandler_KeyDown() {
    try {

        if (event.keyCode == 13 && event.srcElement.type != 'button' && event.srcElement.type != 'submit' && event.srcElement.type != 'textarea') {
            var i, j;
            var self_form = event.srcElement.form;
            //get current controler index
            for (var i = TabIndex; i < self_form.elements.length ; i++) {
                if (event.srcElement == self_form.elements[i]) {
                    TabIndex = i;
                    break;
                }
            }
            //set focus		
            for (j = TabIndex ; j < self_form.elements.length ; j++) {
                if (self_form.elements[j + 1].type != "hidden" && self_form.elements[j + 1].type != "checkbox" && !self_form.elements[j + 1].readOnly && !self_form.elements[j + 1].disabled) {
                    self_form.elements[j + 1].focus();
                    break;
                }
            }
            event.returnValue = false;
            event.cancel = true;
            return false;
        }
        if (event.keyCode == 13 && (event.srcElement.type == 'button' || event.srcElement.type == 'submit') && event.srcElement.isOpenWait == "True") {
            OpenWaitWindow();
        }
        if (event.keyCode == 13 && event.srcElement.type == 'button' && event.srcElement.id == 'btnHELP') {
            var pathname = self.location.pathname;
            var count = pathname.split("/").length;
            var programname = pathname.split("/")[count - 1].split(".")[0];
            var HelpID = programname.substring(0, programname.length - 1) + "0";
            OpenHelp(HelpID);
        }
        if (event.keyCode == 9)
            TabIndex = 0;

        return true;
    }
    catch (e) {
        TabIndex = 0;
        return true;
    }
}
//---------------------------------------------------------------------------------------

/*
	開啟等待視窗
*/
var _oCalPopUp = null;
function OpenWaitWindow() {
    _oCalPopUp = window.createPopup();
    //var e=window.event.srcElement;
    //var sHTML = "<table cellpadding='0' style='FILTER: progid:DXImageTransform.Microsoft.Gradient(GradientType=0, StartColorStr=#ffffff, EndColorStr=#EAF1FF);' cellspacing='0' style='border-collapse: collapse;table-layout:fixed'>" +
    //"<tr><td style='font-size:11px;font-family:Tahoma;text-align:left;border:1px solid #7b9ebd;height:50px;width:300px'>&nbsp;&nbsp;&nbsp;請稍候，資料處理中.....</td></tr>" + 
    //"</table>";

    var sHTML = "<div id='myid' style='position:absolute; top:0; left:0; width:400px; height:110px; background:#cccccc; border:1px solid black; border-top:1px solid white; border-left:1px solid white; padding:1px;  font:normal 10pt tahoma; padding-left:1px '>" +
                        "<table width='100%'  height='4px' style='border:1px solid #cccccc; border-top:1px solid #ffffff; border-left:1px solid #cccccc;FILTER: progid:DXImageTransform.Microsoft.Gradient(GradientType=1, StartColorStr=#000099, EndColorStr=#00CCFF);color:#FFFFFF' ><tr><td style='font-size:11px;'><b>&nbsp; Message Box </b><tr><td></table>" +
                        "<div style='width:220px;height:4px ;font-family:tahoma; line-height:1.5em'>&nbsp;&nbsp;&nbsp;" +
                        "<table><tr><td style='width:25%'><img src='../images/warning.gif'></td><td style='width:75%;font-size:11px'>請稍候，資料處理中.....</td></tr></table><br>" +
                        "</div>"
    _oCalPopUp.document.body.innerHTML = sHTML;
    _oCalPopUp.show(250, 250, 400, 110, document.body);

}
//---------------------------------------------------------------------------------------

/*
	控制滑鼠的事件	
*/
function EventHandler_MouseDown() {
    try {

        if ((event.srcElement.type == 'button' || event.srcElement.type == 'submit') && event.srcElement.isOpenWait == "True") {
            OpenWaitWindow();
        }
        if (event.srcElement.type == 'button' && event.srcElement.id == 'btnHELP') {
            var pathname = self.location.pathname;
            var count = pathname.split("/").length;
            var programname = pathname.split("/")[count - 1].split(".")[0];
            var HelpID = programname.substring(0, programname.length - 1) + "0";
            OpenHelp(HelpID);
        }
    }
    catch (e) {
        ShowError(e.message);
    }
    finally {
        TabIndex = 0;
    }
}
//---------------------------------------------------------------------------------------

/*
	函式功能 : 加入一個下拉式選單的選項

	傳入值 :  物件編號 , 呈現資料 , 資料值

	傳出值 : null
*/
function addOption(objList, text, value) {
    var index = objList.options.length;
    objList.options[index] = new Option(text, value);
    objList.selectedIndex = index;
}
//---------------------------------------------------------------------------------------

/*
	函式功能 : 清除下拉式選單的選項
	傳入值 :  物件編號 
	傳出值 : null
*/
function clearOption(objList) {
    while (objList.options.length != 0) {
        objList.options.remove(objList.options.length - 1);
    }
}
//---------------------------------------------------------------------------------------


function AddCboItem(Obj, Text, Text1) {
    var opt = document.createElement("OPTION");
    opt.value = Text;
    opt.text = Text1;
    Obj.options.add(opt);
}
//---------------------------------------------------------------------------------------

function ClearCob(Obj) {
    while (Obj.options.length != 0) {
        Obj.options.remove(0);
    }
}

//---------------------------------------------------------------------------------------

function SelectedByValue(obj_name, obj_value) {
    var i = 0;
    var f = document.forms[0];
    for (i = 0; i < f.elements[obj_name].length; i++) {

        if ((f.elements[obj_name].options[i].value) == (obj_value)) {

            f.elements[obj_name].options[i].selected = true;
            break;
        } else {
            continue;
        }
    }
}

//Adams:舊有Microsoft.XMLDOM透過ID取得Message資料 mark by Adams
//function GetMessageByID(ID) {

//    //
//    var XmlDocument = null;
//    try {
//        addFormNode("ServiceAgent", "GetLanguageMessage");
//        addCommandNode("ServerInfo", "sel");
//        addParameterNode("MSGID", "string", ID);

//        // 
//        var xmlstr = getXML();

//        //
//        XmlDocument = ExecuteQuery(xmlstr);
//        return XmlDocument;
//    }
//    catch (e) {
//        return e;
//    }
//    finally {
//        delete (XmlDocument);
//    }
//}
//---------------------------------------------------------------------------------------

/*
	函式功能 :取得系統日期
	傳入值 : "date","time"
	
	傳出值 : string(YYYYMMDD)
*/
function getServerInfoByClient(dataType, DataFormat) {
    var xmlstr = "";
    try {
        var ReturnValue = "";
        if (dataType == null)

        { ShowError("Please"); return; }
        if (DataFormat == null && dataType == "date")
            DataFormat = "yyyyMMdd";
        if (DataFormat == null && dataType == "time")
            DataFormat = "hhmmss";


        xmlstr = "<form id=\"ServiceAgent\" method=\"ServerInfoByClinetMethod\">"
                        + "<command id=\"ServerInfo\" action=\"sel\">"
                        + "<parameter id=\"dataType\" type=\"string\">" + dataType + "</parameter>"
                        + "<parameter id=\"DataFormat\" type=\"string\">" + DataFormat + "</parameter>"
                        + "</command>"
                        + "</form>"


        XmlDocu = ExecuteQuery(xmlstr);
        ReturnValue = XmlDocu.text;
    }
    catch (e) {
        return e;
    }
    finally {
        delete (XmlDocu);
        return ReturnValue;
    }
}
//---------------------------------------------------------------------------------------

/*
creator : Pony
函式說明:計算兩個日期的差異天數
傳入值 : oDate1:終止日期，oDate2:起始日期
傳出值 : 天數
*/
function CACL_DATE(oDate1, oDate2) {
    oYear1 = oDate1.substr(0, 4);
    oMonth1 = oDate1.substr(4, 2) - 1;
    oDay1 = oDate1.substr(6, 2);
    oYear2 = oDate2.substr(0, 4);
    oMonth2 = oDate2.substr(4, 2) - 1;
    oDay2 = oDate2.substr(6, 2);

    var next1 = new Date(oYear1, oMonth1, oDay1);
    var next2 = new Date(oYear2, oMonth2, oDay2);
    var nc = Math.ceil((next1.getTime() - next2.getTime()) / (24 * 60 * 60 * 1000));
    return nc;
}
//---------------------------------------------------------------------------------------
/*
creator : Vicky
函式說明:計算某個日期加上天數(秒數，時數，星期，年，月等)
傳入值 : strInterval:TYPE，NumDay:天數，dtDate:日期
傳出值 : 天數
*/
function DateAdd(strInterval, NumDay, dtDate) {
    var XmlDocu_s = null;
    addFormNode("FunctionHandler", "DateAdd");
    addCommandNode("DateAdd", "sel");
    addParameterNode("strInterval", "string", strInterval);
    addParameterNode("NumDay", "string", NumDay);
    addParameterNode("dtDate", "string", dtDate);

    xmlstr_s = getXML();
    XmlDocu_s = ExecuteQuery(xmlstr_s);
    ReturnValue = XmlDocu_s.text;
    return ReturnValue

}
//---------------------------------------------------------------------------------------

/*
creator : Vicky
函式說明:計算兩日期差距(秒數，時數，星期，年，月等)
傳入值 : strInterval:TYPE，NumDay:天數，dtDate:日期
傳出值 : 天數
*/
//?DateDiff("m","20021201","20041201")

function DateDiff(strInterval, dtStart, dtEnd) {
    oYear1 = dtStart.substr(0, 4);
    oMonth1 = dtStart.substr(4, 2) - 1;//javascript的月份從0開始
    oDay1 = dtStart.substr(6, 2);
    var dtStart = new Date(oYear1, oMonth1, oDay1);
    if (isNaN(dtStart)) dtStart = new Date();

    oYear2 = dtEnd.substr(0, 4);
    oMonth2 = dtEnd.substr(4, 2) - 1;//javascript的月份從0開始
    oDay2 = dtEnd.substr(6, 2);
    var dtEnd = new Date(oYear2, oMonth2, oDay2);
    if (isNaN(dtEnd)) dtEnd = new Date();
    switch (strInterval) {
        case "s": return parseInt((dtEnd - dtStart) / 1000);
        case "n": return parseInt((dtEnd - dtStart) / 60000);
        case "h": return parseInt((dtEnd - dtStart) / 3600000);
        case "d": return parseInt((dtEnd - dtStart) / 86400000);
        case "w": return parseInt((dtEnd - dtStart) / (86400000 * 7));
        case "m": return (dtEnd.getMonth() + 1) + ((dtEnd.getFullYear() - dtStart.getFullYear()) * 12) - (dtStart.getMonth() + 1);
        case "y": return dtEnd.getFullYear() - dtStart.getFullYear();
    }
}
//---------------------------------------------------------------------------------------

/*
	creator :Titan Xei
	傳入物件 : TextBox Controler
	傳出 : null
*/
function InputTextBoxEnableView(Controler, Enable) {
    Controler.readOnly = Enable;
    if (Enable) {
        Controler.className = "readonly";
    }
    else {
        Controler.className = "text";
        Controler.disabled = false;
    }
}

function QueryBoxEnableView(Controler, Enable) {
    try {
        var imgID = "img_" + Controler.id;
        InputTextBoxEnableView(Controler, Enable);
        if (Enable)
            Controler.parentElement.document.getElementById(imgID).style.display = "none";
        else
            Controler.parentElement.document.getElementById(imgID).style.display = "";
    }
    catch (e) {
        ShowError(e.message);
    }
}
//---------------------------------------------------------------------------------------

/*
	清除表格資料
*/
function ClearTableRow(targetTable) {
    while (targetTable.rows.length > 0) {
        targetTable.deleteRow(targetTable.rows.length - 1);
    }
}
//---------------------------------------------------------------------------------------

/*
creator : Jacky
函式說明: 取得使用者登入資訊

傳出值 : 使用者登入資訊

*/
function getUserInfo() {
    try {
        var USER = new Object();
        //取得使用者ID
        USER.id = window.parent.frames["top"].document.frames(0).document.getElementById("lblUSER_ID").innerText;
        USER.Name = window.parent.frames["top"].document.frames(0).document.getElementById("lblUSER_NAME").innerText;
        //取得部門ID
        USER.DeptId = window.parent.frames["top"].document.frames(0).document.getElementById("lblDEPT_NO").innerText;
        USER.DeptName = window.parent.frames["top"].document.frames(0).document.getElementById("lblDEPT_NAME").innerText;
        USER.CompanyName = "EVA AIRWAYS CORPORATION";
        USER.IsManger = true;
        return USER;
    }
    catch (e) {
        ShowError(e.Message);
    }
    finally {

    }
}
//---------------------------------------------------------------------------------------

function CheckStatus() {
    var target = event.srcElement;
    var oRow = target.parentElement.parentElement;
    var i = oRow.rowIndex;
    var objControl = new Object();
    for (var j = 0; j < DetailTable.rows[i].cells.length; j++) {
        for (var k = 0; k < DetailTable.rows[i].cells[j].children.length; k++) {
            if (target.checked) {
                //DetailTable.rows[i].cells[j].children[k].value="";
                DetailTable.rows[i].cells[j].children[k].readOnly = true;
                objControl.id = DetailTable.rows[i].cells[j].children[k].name;
                //update by samantha --勾選時把原本自己產生的錯誤隱藏起來

                ErrHandler_Visible_Item(objControl, false);
            }
            else {
                if (DetailTable.rows[i].cells[j].children[k].type == "text" && DetailTable.rows[i].cells[j].children[k].className == 'text') {
                    DetailTable.rows[i].cells[j].children[k].readOnly = false;
                }
                else if (DetailTable.rows[i].cells[j].children[k].type == "text" && DetailTable.rows[i].cells[j].children[k].className == 'number') {
                    DetailTable.rows[i].cells[j].children[k].readOnly = false;
                }
                objControl.id = DetailTable.rows[i].cells[j].children[k].name;
                //update by samantha --沒勾選時把原本自己產生的錯誤隱藏起來恢復顯現出來
                ErrHandler_Visible_Item(objControl, true);
            }

        }
    }


}
//---------------------------------------------------------------------------------------

/*
	功能 : 轉換數字
	Creator : Titan Xei
*/
function ToNumber(NumberDate) {
    if (Trim(NumberDate) == "") {
        return 0;
    }
    else {
        return Number(Trim(NumberDate));
    }
}
//---------------------------------------------------------------------------------------

/*
	功能 :	開啟WorkFlow Remark 視窗
	Creator : Titan Xei
	傳入參數 : trans_no = 單據編號 , status = 狀態 , DefaultReMark = 預設備註 
*/
function OpenWorkFlowRemark(trans_no, status, DefaultReMark) {
    var _DialogWidth = "320px";
    var _DialogHeight = "280px";
    var dialogStr = "dialogWidth=" + _DialogWidth + ";dialogHeight=" + _DialogHeight + ";center=yes;border=thin;help=no;status=no;resizable=no;";
    var QueryCondition = "trans_no=" + trans_no + "&status=" + status;
    var TargetURL = "../WorkFlowRemark.aspx?"
    try {
        if (trans_no != null && status != null)
            TargetURL = TargetURL + QueryCondition;
        if (DefaultReMark != null)
            TargetURL = TargetURL + "&DefaultReMark=" + DefaultReMark;
        return window.showModalDialog(TargetURL, self, dialogStr, true);
    }
    catch (e) {
        ShowError(e.message);
    }

}
//---------------------------------------------------------------------------------------

function DEPT_FLT_NO_CHANGE() {
    try {
        if ($("#txtDEPT_FLT_NO").val().length > 0) {
            if (isNaN($("#txtDEPT_FLT_NO").val())) {
                //Ken:WTF
                //document.all.txtDEPT_FLT_NO.value = document.all.txtDEPT_FLT_NO.value;
            }
            else {
                $("#txtDEPT_FLT_NO").val('BR' + $("#txtDEPT_FLT_NO").val());
            }
        }
    }
    catch (e) {
        ShowError(e.message);
    }
}
//---------------------------------------------------------------------------------------

function chk_REF(ISSUETYPE, TYPE, REF1, REF2, DEPT, STORE) {
    try {
        var Message = new Object();
        Message.msg = ''
        if (ISSUETYPE.value == 'A1') {
            if (Trim(REF1.value) != 'INTL' && Trim(REF1.value) != 'DOM') {
                Message.msg = '必需為INTL 或 DOM！'
                Message.object = REF1

            }
        }
        if (Trim(ISSUETYPE.value) == 'A3' && Trim(DEPT.value) != 'Y202') {
            Message.msg = '必需是Y202！'
            Message.object = DEPT
        }
        if (TYPE == 'C' && ISSUETYPE.value == 'A3' && Trim(REF2.value) == '') {
            Message.msg = '不可空白'
            Message.object = REF2
        }
        if (Trim(STORE) == 'TEMO' && ISSUETYPE.value != 'C') {
            Message.msg = "待報廢料只接受ISSUE_TYPE為'C'之單據"
            Message.object = ISSUETYPE

        }
    }
    catch (e) {
        ShowError(e.message);
    }
    return Message;
}

//-----------------------------------------------------------------------------------------------
function ToUpperString(o) {
    return isNaN(o) && o != null ? o.toUpperCase() : o;
}
//---------------------------------------------------------------------------------------

//檢核日期
function check_date(sTmpVal) {
    if (sTmpVal.length < 10) {
        return false;
    }

    for (var i = 0; i < sTmpVal.length; i++) {
        var letter = sTmpVal.substring(i, i + 1);
        if ((letter < "0" || "9" < letter) && letter != "\/") {
            return false;
        }

    }
    for (var i = 0; i < 4; i++) {
        var letterYY = sTmpVal.substring(i, i + 1);
        if (letterYY < "0" || "9" < letterYY) {
            return false;
        }
    }
    var iYear = parseInt(sTmpVal.substring(0, 4));

    for (var i = 5; i < 7; i++) {
        var letterMM = sTmpVal.substring(i, i + 1);
        if (letterMM < "0" || "9" < letterMM) {
            return false;
        }
    }
    var sDummy = sTmpVal.substring(5, 6);
    if (sDummy == "0") {
        sDummy = sTmpVal.substring(6, 7);
    }
    else {
        sDummy = sTmpVal.substring(5, 7);
    }
    var iMonth = parseInt(sDummy);
    if (iMonth < 1 || 12 < iMonth) {
        return false;
    }
    for (var i = 8; i < 10; i++) {
        var letterDD = sTmpVal.substring(i, i + 1);

        if (letterDD < "0" || "9" < letterDD) {
            return false;
        }
    }

    var sDummy1 = sTmpVal.substring(8, 9);
    if (sDummy1 == "0") {
        sDummy1 = sTmpVal.substring(9, 10);
    }
    else {
        sDummy1 = sTmpVal.substring(8, 10);
    }
    var iDay = parseInt(sDummy1);

    if (iDay < 1 || 31 < iDay) {
        return false;
    } else if ((iMonth == 4 || iMonth == 6 || iMonth == 9 || iMonth == 11) && (iDay < 1 || 30 < iDay)) {
        return false;
    } else if (iMonth == 2 && (iDay < 1 || 29 < iDay)) {
        return false;
    } else if (iMonth == 2 && LeapYear(iYear) == false && (iDay < 1 || 28 < iDay)) {
        return false;
    }
    return true;
}
//---------------------------------------------------------------------------------------
// 閏年判斷函式
function LeapYear(intYear) {
    if (intYear % 100 == 0) {
        if (intYear % 400 == 0) { return true; }
    }
    else {
        if ((intYear % 4) == 0) { return true; }
    }
    return false;
}

//---------------------------------------------------------------------------------------
var OpenHelpWindow = null;
function OpenHelp(HelpID) {
    if (HelpID == null) {
        var pathname = top.frames["main"].location.pathname;
        var count = pathname.split("/").length;
        var HelpID = pathname.split("/")[count - 1].split(".")[0];
    }
    var hostAddress = document.location.protocol + "//" + document.location.host + "//smas//";
    var HelpURL1 = hostAddress + "help//" + HelpID + ".htm";
    var HelpURL2 = hostAddress + "help//" + HelpID + "_en.htm";
    var sXPos = window.screen.height;
    var sYPos = 0;
    window.enlink = HelpURL2;
    window.link = HelpURL1;
    var sWStyle = "dialogLeft=" + sXPos + ";dialogHeight=710px;dialogWidth=680px;help=no;scrollbars=1;menubar=1; location=1; resizable=yes; status=0"
    if (OpenHelpWindow == null || OpenHelpWindow.closed) {
        OpenHelpWindow = window.showModelessDialog(hostAddress + "HelpFrame.htm", window, sWStyle);
    }
    else {
        OpenHelpWindow.focus();
    }
}

function PUBLIC_DateAdd(timeU, byMany, dateObj) {
    var millisecond = 1;
    var second = millisecond * 1000;
    var minute = second * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var year = day * 365;

    var newDate;
    var dVal = dateObj.valueOf();
    switch (timeU) {
        case "ms": newDate = new Date(dVal + millisecond * byMany); break;
        case "s": newDate = new Date(dVal + second * byMany); break;
        case "mi": newDate = new Date(dVal + minute * byMany); break;
        case "h": newDate = new Date(dVal + hour * byMany); break;
        case "d": newDate = new Date(dVal + day * byMany); break;
        case "y": newDate = new Date(dVal + year * byMany); break;
    }


    var oYear = newDate.getYear();
    var oMonth = newDate.getMonth() + 1;
    var oDate = newDate.getDate();
    if (parseInt(oMonth) < 10) {
        oMonth = "0" + oMonth;
    }

    if (parseInt(oDate) < 10) {
        oDate = "0" + oDate;
    }


    var oYMD = String(oYear) + String(oMonth) + String(oDate);
    return oYMD;
}
//Update By Titan 
//設定網頁重新載入
function FN_ReSubmit() {
    //var oForm = document.forms[0];
    //var Controler = document.createElement("INPUT");
    //Controler.id = "IsReSubmit";
    //Controler.name = "IsReSubmit";
    //Controler.type = "hidden";
    //Controler.value = "Y";
    //oForm.insertBefore(Controler);
    //oForm.submit();

    //Update By Tony 2014/07/23
    var $btn = $(window.opener.document).find("#btnSearch");
    if ($btn.length > 0) {
        $btn.trigger("click");
    }
    else {
        window.opener.location.reload();
    }

    //not working
    //var $btn = $("<input type='submit' name='IsReSubmit' value='' id='IsReSubmit'>")
    //$btn.appendTo(window.opener.document.forms[0]);
}
/*//檢查分頁跳頁索引值

function FN_CheckGotoPageIndex()
{
	document.all["GotoPage"].value = parseInt(document.all["GotoPage"].value);
	var index	= Number(document.all["PageIndex"].value);
	var count =Number(document.all["PageCount"].value);
	var gotopage = Number(document.all["GotoPage"].value);
	var btnGo = document.all["btnGo"];
	if(gotopage > count || gotopage <= 0 || isNaN(gotopage) ){
		btnGo.disabled = true;
	}
	else{
		btnGo.disabled = false;
	}
}*/
function isDate(v) {
    var r = v.match(/^(\d{1,4})(|\/)(\d{1,2})\2(\d{1,2})$/);
    if (r == null)
        return false;
    var d = new Date(r[1], r[3] - 1, r[4]);
    return (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4]);
}

//-----以下為專案升級所使用之新函式-----

//取得目錄
function GetLocalPath() {
    //var m_Path = $(location).attr('href').substr(0, $(location).attr('href').toUpperCase().indexOf('SMASB2B') + ('SMASB2B').length);
    var m_path = window.location.protocol + "//" + window.location.host + "/smasb2b";
    return m_Path;
}

//Adams:透過jQuery AJAX方式設定控制項Message資料(使用回傳值)
function GetMessageByID(ID) {   
    var msg = document.createElement("TITLE");    
    try {
        $.ajax({
            type: "POST",
            async: false,
            url: GetLocalPath() + "/GetMessageID.asmx/GetLanguageMessage",
            dataType: 'json',
            contentType: "application/json;charset=utf-8",
            data: "{ 'MSGID': '" + ID + "' }",
            success: function (data) {
                msg.text = data.d               
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);                
            }
        });        
    }
    catch (e) {
        return e;
    }
    return msg;    
}